/* eslint-disable no-undef */
const dgram = require("dgram");
const server = dgram.createSocket("udp4");
server.on("message", (msg, rinfo) => {
  // 从文件中查询负载最小的服务器
  fs.readFile("./message.json", function (err, data) {
    if (err) {
      return console.error(err);
    }
    var config = JSON.parse(data);
    var server_host = config.address;
    console.log(
      "负载均衡器收到消息，选择负载最小的服务器转发请求%s",
      server_host
    );
    // 向负载最小的服务器转发
    forward(msg, rinfo, server_host);
  });
});

server.on("error", (err) => {
  console.log("server error:" + err.stack);
  server.close();
});
server.on("listening", () => {
  const addr = server.address();
  console.log(`run ${addr.address}:${addr.port}`);
});
server.bind(53);

function forward(msg, rinfo, server_host) {
  console.log(rinfo);
  const client = dgram.createSocket("udp4");
  client.on("error", (err) => {
    console.log(`client error:` + err.stack);
    client.close();
  });
  client.on("message", (fMsg) => {
    console.log("load_balancer 收到反馈并发送给客户端");
    server.send(fMsg, rinfo.port, rinfo.address, (err) => {
      err && console.log(err);
    });
    client.close();
  });
  client.send(msg, 53, server_host, (err) => {
    if (err) {
      console.log(err);
      client.close();
    }
  });
}
